const express = require('express');
const router = express.Router();
const { Article } = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFound } = require('http-errors');
const { Op } = require('sequelize');
const { getKey, setKey } = require('../utils/redis');

/**
 * 查询文章列表
 *
 * GET /articles
 * */

router.get('/', async function (req, res) {
  try {
    const query = req.query;
    console.log(req.query);
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;

    const cacheKey = `articles:${currentPage}:${pageSize}`;
    let data = await getKey(cacheKey);
    if (data) {
      return success(res, '查询Redis数据成功', {
        articles: rows,
        pagination: {
          total: count,
          currentPage,
          pageSize,
        },
      });
    }
    const condition = {
      attributes: { exclude: ['content'] },
      order: [['id', 'desc']],
      limit: pageSize,
      offset,
    };

    const { count, rows } = await Article.findAndCountAll(condition);

    const _data = {
      articles: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    await setKey(cacheKey, _data);

    success(res, '查询成功', _data);
  } catch (error) {
    failure(res, error);
  }
});

/***
 * 查询文章详情
 * */
router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;
    const article = await Article.findByPk(id);
    if (!article) {
      throw new NotFound(`ID: ${id} 文章未找到`);
    }

    success(res, '查询成功', { article });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
